import java.util.ArrayList;
import java.util.List;
//https://leetcode.cn/problems/count-of-smaller-numbers-after-self/

class Solution1 {
    int[] ret;
    int[] index;
    int[] tmpIndex;
    int[] tmpNums;

    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        ret = new int[n];
        index = new int[n];
        tmpIndex = new int[n];
        tmpNums = new int[n];

        //初始化 index 数组
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }

        mergeSort(nums, 0, n - 1);

        List<Integer> list = new ArrayList<>();
        for (int x : ret) {
            list.add(x);
        }
        return list;
    }

    private void mergeSort(int[] nums, int begin, int end) {
        if (begin >= end) return;
        int mid = (begin + end) / 2;
        //[left,mid] [mid+1,right]

        //处理左右两个区间
        mergeSort(nums, begin, mid);
        mergeSort(nums, mid + 1, end);

        //处理一左一右的情况
        int cur1 = begin, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= end) {
            if (nums[cur1] > nums[cur2]) {
                ret[index[cur1]] += end - cur2 + 1;
                tmpIndex[i] = index[cur1];
                tmpNums[i++] = nums[cur1++];
            } else {
                tmpIndex[i] = index[cur2];
                tmpNums[i++] = nums[cur2++];
            }
        }
        while (cur1 <= mid) {
            tmpIndex[i] = index[cur1];
            tmpNums[i++] = nums[cur1++];
        }
        while (cur2 <= end) {
            tmpIndex[i] = index[cur2];
            tmpNums[i++] = nums[cur2++];
        }

        for (int j = begin; j <= end; j++) {
            nums[j] = tmpNums[j - begin];
            index[j] = tmpIndex[j - begin];
        }
    }
}

class Solution {
    public int reversePairs(int[] nums) {
        return mergeSort(nums,0,nums.length-1);
    }
    public int mergeSort(int[] nums,int begin,int end) {
        if(begin>=end) return 0;
        int ret = 0;
        int mid = (begin+end)/2;
        int[] tmp = new int[end-begin+1];

        ret += mergeSort(nums,begin,mid);
        ret += mergeSort(nums,mid+1,end);

        int cur1 = begin,cur2 = mid+1, i=0;
        while(cur1<=mid && cur2<=end) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1++];
            }else {
                ret += mid - cur1 + 1;
                tmp[i++] = nums[cur2++];
            }
        }
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= end) {
            tmp[i++] = nums[cur2++];
        }
        for(int j = begin; j<=end; j++) {
            nums[j] = tmp[j-begin];
        }
        return ret;
    }
}

public class Test {
    public static void main(String[] args) {

    }
}
